Calling REST API


Irrespective of UI Framework or Library we think of using for our application development, let it be React or Angular, it is very much needed for our Application’s UI to interact with REST API’s for Performing Various Operations like getting the data from the Database or to store the Data into the database or to delete the data from the database or any other business logic execution which should happen on the server.

In this article, we will understand how do we make API Call from React to get the List of Employees. In Order to make this happen, we have to create two different Projects. First one is building a Web API which will return the List of Employees. Second One is developing a React based Application which will call this API, get the List of Employees and display in the Application.

So lets start building our REST API using ASP.NET Web API Platform. I use Visual Studio to build our Web API. Lets Open Visual Studio. Click on Create a New Project option available on the Right handside. Lets search for Asp.Net Web Application, Select the Asp.Net Web Appplication template and Click on Next. Name this as WebAPI_React_Client, Select the Respective location where you want to store this Project and Click on Create.

As One can see Empty Template is Selected by default and we will use the same. On the Right hand side of the Window, Please Select Web API Checkbox under Add Folders and Core References Section and Click on Create. Now lets go to Solution Explorer, right Click on Models folder and create a New Class and we can name it as Employee. Lets add Properties like Id, Name, Location and Salary to this Class. Now lets go to Solution Explorer, right Click on Controller folder and select Add Controller Option. Lets Select Web API 2 Controller-Empty template and Click on Add.

We will name this Controller as Employee Controller and lets Click on Add. Now the EmployeeController Class is generated. I will go and add a Method GetAll which will be returning List of Employees. I have the Code handy and Pasting it here.

public List<Employee> GetAll()
        {
            List<Employee> empList = new List<Employee>
            {
                new Employee{Id=101,Name="Abhinav",Location="Bangalore",Salary=12345},

                new Employee{Id=102,Name="Abhishek",Location="Chennai",Salary=23456},

                new Employee{Id=103,Name="Akshay",Location="Bangalore",Salary=34567},

                new Employee{Id=104,Name="Akash",Location="Chennai",Salary=45678},

                new Employee{Id=105,Name="Anil",Location="Bangalore",Salary=56789}
            };
            return empList;
        }

In Order to allow any other Projects to access this Web API, we have to enable CORS. So lets go to Solution Explorer again, right click on references, Select Manage NuGet Packages.

Lets switch to Browse Tab, search for Microsoft.AspNet.WebApi.Cors. From the search results, lets select the first one and click on the Install button which is available on the right hand side.

Click on Ok button in the dialog box which is Prompted. Click on the I  Accept button and Complete the Process. Lets go to Solution Explorer, expand App_Start, one can notice WebApiConfig.cs and Open this file.

Enable the CORS support for our Project by calling config.EnableCors method with in Register Method. Now lets go to our EmployeeController Class, apply EnableCors attribute to this Class. We can find this EnableCors Attribute Class with in System.Web.Http.Cors namespace. To this EnableCors attribute, we have to pass the list of Origins, headers and methods we want to allow. We will allow any origin, any header and any method to access this api by passing *, * and *. With this we are done with Creating our Rest API. Lets run this Project using Ctrl + F5. 

In the browser, lets try to access our Employee Api by appending api/Employee to the URL and we can see that list of Employees are being returned from our Api. So we are done with Part 1 and now we have to call this API from our React Project to get this list of Employees.

Lets Open Index.js file from our demo Project using Visual Studio Code. Lets create a class EmployeeComponent which extends React.Component Class.

class EmployeeComponent extends React.Component {
}

We will create a Constructor which accepts props as the parameter and lets pass this props to the baseclass constructor. Lets create state object, add a property employees and initialize it to empty array.

constructor(props) {
    super(props);
    this.state = {
      employees: []
    };
  }

Now we will implement render method. From this render method, we will return a div container. In this div, we will create a table which is displaying the list of employees.

render() {
    return (
      <div>
        <h2>Employees Data...</h2>
        <table>
          <thead>
            <tr>
              <th>Id</th>
              <th>Name</th>
              <th>Location</th>
              <th>Salary</th>
            </tr>
          </thead>
          <tbody>         
          </tbody>
        </table>
      </div>
      );
    }

Now we have to iterate through the employees array from our state object and we do that using map method. We  create the number of table rows based on the number of elements with in this employees array. With in every row, we will display the employee details by placing this code.

{this.state.employees.map(emp => (
            <tr key={emp.Id}>
              <td>{emp.Id}</td>
              <td>{emp.Name}</td>
              <td>{emp.Location}</td>
              <td>{emp.Salary}</td>
              </tr>
  ))}

Lets call this Component and render it to our root Container.

const element=<EmployeeComponent></EmployeeComponent>

ReactDOM.render(element,document.getElementById("root"));

Save these changes, lets navigate to the browser and observe the output. Our table is empty without any data. That is because we are yet to call our Rest API from our react application. 

Now question is where should we write the code of sending the API request with in our EmployeeComponent Class. We want to execute some code which fetches the list of employees from Rest API whenever the EmployeeComponent is rendered to the DOM. This is called “mounting” in React. We can declare special methods on the component class to run some code when a component mounts.

These methods are called “lifecycle methods”. React Component Classes has lifecycle methods, one of such method is componentDidMount.  using this method we can run some code when the respective component is rendered to the DOM. Lets go ahead and implement this method in our Component Class.

componentDidMount() {

  }

Now the next question is how do we send the AJAX Request from our React Application. This can be done by using any AJAX library we like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch. In this example, we will make use of fetch to make API Call and about the usage of other AJAX libraries in React, we will discuss in our upcoming sessions.

We call fetch method and we will pass the Url of Web API. This is the Url where our Web API is available and I paste it here. We call the Promise method using then, convert the response into JSON objects, and then we assign this result list to our state object employees property using setState method.

Fetch(“https://localhost:44301/api/Employee”)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            employees: result
          });
        }
      );

Lets save these changes, navigate to the browser and we can see the employee details in our table. As one can see, It is very easy to make API Communication from our React.

For Video Reference





© 2020 Pragimtech. All Rights Reserved.